var conf = null;
function init(config) {
	conf = config || {};
}

var env = {};
function set_env(key, value) {
	env[key] = value;
}

function send(uri, data, callback) {
	let post = {
		uri: uri,
		env: env,
		data: data
	};

	wx.request({
		method: 'POST',
		url: conf.remote,
		data: post,
		header: {'content-type': 'application/json'},
		success: function (res) {
			if (callback) {
				let response = res.data;
				if (response.code != 0) {
					callback(response, null);
				}
				else {
					callback(null, response.result);
				}
			}
		}
	});
}

function upload(uri, file, callback) {
	wx.uploadFile({
		url: conf.remote,
		name: 'data',
		filePath: file,
		formData: {uri: uri, env: env},
		success: function (res) {
			let err = null;
			let data = JSON.parse(res.data);

			if (data && data.code == 0) {
				data = data.data;
			}
			else {
				err = data;
				data = null;
			}

			if (callback) {
				callback(err, data);
			}
		},
		fail: function (err) {
			if (callback) {
				callback({code: 500, message: err || 'upload error'})
			}
		}
	});
}

module.exports = {
	init, set_env, send, upload
};